//
//  AddBabyViewController.m
//  MM
//
//  Created by 郑渊文 on 5/19/15.
//  Copyright (c) 2015 王晨辉. All rights reserved.
//

#import "AddBabyViewController.h"
#import "CommonMacro.h"
#import "ComBoxView.h"
#import "ZHPickView.h"
#import "LMContainsLMComboxScrollView.h"
#import "ProvinceViewController.h"
#import "areaManager.h"
#import "myTabBarViewController.h"

#define kDropDownListTag 1000
@interface AddBabyViewController ()<ZHPickViewDelegate,UITextFieldDelegate>
{
    NSString *ifboy;
    LMContainsLMComboxScrollView *bgScrollView;
    NSString *selectedArea;
    UIButton *backBtn;
    UIButton *selectGirlBtn;
    UIButton *selectBoyBtn;
    UIView *myBgView;
    UIButton *chooseBtn;
    UIButton *makeSureBtn;
}

@property(nonatomic,copy)ZHPickView *pickview;
@property(nonatomic,copy)NSString *areaStr;
@property(nonatomic,copy)NSString *_areaStrTs;
@property(nonatomic,copy)NSMutableArray *areaArray;
@property(nonatomic,copy)NSString *birthdayTime;
@property(nonatomic,copy)UITextField *babyName;
@end

@implementation AddBabyViewController

- (NSMutableArray *)areaArray
{
    if (nil == _areaArray) {
        _areaArray = [NSMutableArray array];
    }
    return _areaArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.view addGestureRecognizer:tap];
    ifboy = @"";
    self.view.backgroundColor = [UIColor whiteColor];
    //    self.navigationController.navigationBarHidden = YES;
    
    [self initSubViews];
    
    _babyName.delegate = self;
    _areaArray = [NSMutableArray array];
    
    NSArray *stringArray = [NSArray arrayWithObjects:@"abc ", @"abcd", @"abc 12",@"abc 13",@"abc 05",nil];
    NSComparator sortBlock = ^(id string1, id string2)
    {
        return [string2 compare:string1];
    };
    NSArray *sortArray = [stringArray sortedArrayUsingComparator:sortBlock];
    
    
    if ([self.city integerValue] == 1) {
        //NSLog(@"1111");
        [areaManager shareInstance].areaId =nil;
        
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
                                     initWithTitle:@"地址"
                                     style:UIBarButtonItemStylePlain
                                     target:self
                                     action:@selector(chooseArea)];
        [rightBtn setTintColor:[UIColor whiteColor]];
        self.navigationItem.rightBarButtonItem = rightBtn;

    } else {
        
        //NSLog(@"2222");

    }
    
    ////NSLog(@"sortArray:%@", sortArray);
    // Do any additional setup after loading the view.
}
-(void)viewWillAppear:(BOOL)animated{
    
    //NSLog(@"%@",[areaManager shareInstance].areaId);

    
}
-(void)viewDidAppear:(BOOL)animated
{
    
    //NSLog(@"%@",[areaManager shareInstance].areaId);

    

    if([areaManager shareInstance].areaId ==nil)
    {
        _areaStr =@"地址";
        
        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
                                     initWithTitle:_areaStr
                                     style:UIBarButtonItemStylePlain
                                     target:self
                                     action:@selector(chooseArea)];
        [rightBtn setTintColor:[UIColor whiteColor]];
        self.navigationItem.rightBarButtonItem = rightBtn;

    }else if([areaManager shareInstance].areaId)
    {
        
        
//        _areaStr = [NSString stringWithFormat:@"%@%@%@",[areaManager shareInstance].areaProvince,[areaManager shareInstance].areaCity,[areaManager shareInstance].areaName];
        _areaStr = [NSString stringWithFormat:@"%@"/*,[areaManager shareInstance].areaProvince,[areaManager shareInstance].areaCity*/,[areaManager shareInstance].areaName];
        //右边按钮
        __areaStrTs = [NSString stringWithFormat:@"%@",[areaManager shareInstance].areaCity];
        if ([_areaStr  isEqual: @""]) {
            
            
            UIBarButtonItem *right = [[UIBarButtonItem alloc]
                                      initWithTitle:__areaStrTs
                                      style:UIBarButtonItemStylePlain
                                      target:self
                                      action:@selector(chooseArea)];
            [right setTintColor:[UIColor whiteColor]];
            self.navigationItem.rightBarButtonItem = right;
        } else {
            
            
            UIBarButtonItem *right = [[UIBarButtonItem alloc]
                                      initWithTitle:_areaStr
                                      style:UIBarButtonItemStylePlain
                                      target:self
                                      action:@selector(chooseArea)];
            [right setTintColor:[UIColor whiteColor]];
            self.navigationItem.rightBarButtonItem = right;
            
            
        }
        
        ////NSLog(@"%@",_areaStr);

//        
//        UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc]
//                                     initWithTitle:_areaStr
//                                     style:UIBarButtonItemStylePlain
//                                     target:self
//                                     action:@selector(chooseArea)];
//        [rightBtn setTintColor:[UIColor whiteColor]];
//        self.navigationItem.rightBarButtonItem = rightBtn;
//        
        

//        [areaManager shareInstance].areaName;
        
    }
    
    [chooseBtn setTitle:_areaStr forState:UIControlStateNormal];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)tap:(UITapGestureRecognizer *)recognizer
{
    [_babyName resignFirstResponder];

}
-(void)initSubViews
{
    
    
    //自定义左右按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"_0000_返回.png"]
                      forState:UIControlStateNormal];
    [button addTarget:self action:@selector(back)
     forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(0, 0, 20, 15);
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    self.navigationItem.leftBarButtonItem = menuButton;
    
    self.navigationItem.title = @"我的宝贝";
    [self.navigationController.navigationBar setTranslucent:NO];//设置navigationbar的半透明
    [self.navigationController.navigationBar setBarTintColor:[GetFileModel colorWithHexString:@"#34bd81" alpha:1]];
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    
    if (IS_IPHONE_4_OR_LESS) {
        
        UIScrollView *bgView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        bgView.contentSize = CGSizeMake(SCREEN_WIDTH, 568);
        bgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:bgView];
        myBgView = bgView;
    }
    else
    {
        
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        bgView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:bgView];
        myBgView = bgView;
    }
    
    
    
    //宝宝姓名
    
    UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-40, 10, 80, 40)];
    name.text = @"宝宝姓名";
    name.textColor = [UIColor blackColor];
    name.textAlignment = NSTextAlignmentCenter;
    [myBgView addSubview:name];
    
    //姓名输入框呢
    
    _babyName = [[UITextField alloc]initWithFrame:CGRectMake(60, CGRectGetMaxY(name.frame)+10.0, SCREEN_WIDTH-120, 40)];
    _babyName.text = _mybabyName;
    _babyName.layer.cornerRadius = 5;
    _babyName.layer.borderColor = UIColorWithRGBA(232, 234, 237, 1).CGColor;
    _babyName.layer.borderWidth = 1;
    [myBgView addSubview:_babyName];
    
    
    //    宝宝性别
    
    UILabel *sexLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-40, CGRectGetMaxY(_babyName.frame), 80, 40)];
    sexLable.text = @"宝宝性别";
    sexLable.textColor = [UIColor blackColor];
    sexLable.textAlignment = NSTextAlignmentCenter;
    [myBgView addSubview:sexLable];
    
    
    // 性别图片
    
    selectBoyBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-90, CGRectGetMaxY(sexLable.frame)+10.0, 80, 80)];
    
    [selectBoyBtn setImage:[UIImage imageNamed:@"男孩-未选中"] forState:UIControlStateNormal];
    [selectBoyBtn addTarget:self action:@selector(chooseBoy) forControlEvents:UIControlEventTouchUpInside];
    [myBgView addSubview:selectBoyBtn];
    
    selectGirlBtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(selectBoyBtn.frame)+20, CGRectGetMaxY(sexLable.frame)+10.0, 80, 80)];
    [selectGirlBtn setImage:[UIImage imageNamed:@"女孩-未选中"] forState:UIControlStateNormal];
    [selectGirlBtn addTarget:self action:@selector(chooseGirl) forControlEvents:UIControlEventTouchUpInside];
    [myBgView addSubview:selectGirlBtn];
    
    
    
    // 宝宝年龄
    
    UILabel *ageLable = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/2-40,CGRectGetMaxY(selectGirlBtn.frame)+10, 80, 40)];
    ageLable.text = @"宝宝年龄";
    ageLable.textColor = [UIColor blackColor];
    ageLable.textAlignment = NSTextAlignmentCenter;
    [myBgView addSubview:ageLable];
    
    if ([self.gender integerValue] == 1) {
        
        
        [selectBoyBtn setImage:[UIImage imageNamed:@"男孩-选中状态"] forState:UIControlStateNormal];
        [selectGirlBtn setImage:[UIImage imageNamed:@"女孩-未选中"] forState:UIControlStateNormal];
        
        
    }else if([self.gender integerValue] == 3){
        
        [selectBoyBtn setImage:[UIImage imageNamed:@"男孩-未选中"] forState:UIControlStateNormal];
        [selectGirlBtn setImage:[UIImage imageNamed:@"女孩-未选中"] forState:UIControlStateNormal];
        
        
    }else if([self.gender integerValue] == 0){
        
        [selectBoyBtn setImage:[UIImage imageNamed:@"男孩-未选中"] forState:UIControlStateNormal];
        [selectGirlBtn setImage:[UIImage imageNamed:@"女孩-选中"] forState:UIControlStateNormal];
    }
    
    
    // 生日选择
    
    NSDate *date=[NSDate dateWithTimeIntervalSinceNow:0];
    
    _pickview=[[ZHPickView alloc] initDatePickWithDate:date datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
    _pickview.delegate = self;
    [_pickview setFrame:CGRectMake(0, CGRectGetMaxY(ageLable.frame) -40.0, SCREEN_WIDTH, 200.0)];
    
    [myBgView addSubview:_pickview];
    
    
    if (IS_IPHONE_4_OR_LESS) {
        makeSureBtn = [[UIButton alloc]initWithFrame:CGRectMake(20,568-110, SCREEN_WIDTH-40, 40)];
    }
    
    
    else{
        makeSureBtn = [[UIButton alloc]initWithFrame:CGRectMake(20,myBgView.frame.size.height-110, SCREEN_WIDTH-40, 40)];
    }
    [makeSureBtn setBackgroundImage:[UIImage imageNamed:@"gree@2x"] forState:UIControlStateNormal];
    [makeSureBtn setBackgroundImage:[UIImage imageNamed:@"greeScl@2x"] forState:UIControlStateHighlighted];
    [makeSureBtn setTitle:@"确认" forState:UIControlStateNormal];
    [makeSureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    makeSureBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    makeSureBtn.userInteractionEnabled = YES;
    [makeSureBtn addTarget:self action:@selector(makeSure) forControlEvents:UIControlEventTouchUpInside];
    [myBgView addSubview:makeSureBtn];
    
    
    
    
    
    [myBgView addSubview:chooseBtn];
    
}
-(void)chooseBoy{
    [selectBoyBtn setImage:[UIImage imageNamed:@"男孩-选中状态"] forState:UIControlStateNormal];
    [selectGirlBtn setImage:[UIImage imageNamed:@"女孩-未选中"] forState:UIControlStateNormal];
    ifboy = @"1";
}
-(void)chooseGirl{
    [selectBoyBtn setImage:[UIImage imageNamed:@"男孩-未选中"] forState:UIControlStateNormal];
    [selectGirlBtn setImage:[UIImage imageNamed:@"女孩-选中"] forState:UIControlStateNormal];
    ifboy = @"0";
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_babyName resignFirstResponder];
    return YES;
}

-(void)setUpBgScrollView
{
    
    
    //    xhbox = [[XHDropBoxView alloc]init];
    //    /*第一个参数设置：frame.origin.x 第二个参数：frame.origin.y  第三个参数：textfield宽度 第四个参数：textfield高度  第五个参数：button宽度
    //     第六个参数：tableview的高度 第七个参数：设置是否能够编辑 yes能编辑  no不能编辑
    //     默认button高度和textfiled高度一样
    //     默认tableview宽度为textfield和button的宽度只和*/
    //    [xhbox setControlsViewOriginx:100 ViewOriginy:30 TextWidth:120 TextAndButtonHigth:30 ButtonWidth:20 TableHigth:100 Editortype:YES];
    //    xhbox.textfiled.placeholder = @"所在园区";
    //    xhbox.delegate =self;
    //    xhbox.tag = 1000;
    //    NSArray *arr = @[@"第一个选项",@"第二个选项",@"第三个选项",@"第四个选项"];
    //    xhbox.arr = arr;
    //    [bgScrollView addSubview:xhbox];
    
    // Do any additional setup after loading the view, typically from a nib.
    //    ComBoxView *comBox = [[ComBoxView alloc]initWithFrame:CGRectMake(50, 40, SCREEN_WIDTH-100, 24)];
    //    comBox.backgroundColor = [UIColor whiteColor];
    //    comBox.arrowImgName = @"down_dark0.png";
    //    _areaArray= [NSMutableArray arrayWithArray:@[@"10年8天",@"10年7天",@"10年6天"]];
    //    selectedArea = [_areaArray objectAtIndex:0];
    //    ////NSLog(@"数组中得数据为%@",_areaArray);
    //    comBox.titlesList = _areaArray;
    //    comBox.delegate = self;
    //    comBox.supView = bgScrollView;
    //    [comBox defaultSettings];
    //    comBox.tag = kDropDownListTag;
    //    [bgScrollView addSubview:comBox];
}


//- (void)comBoxView:(ComBoxView *)comBoxView didSelectAtIndex:(NSInteger)index withData:(NSString *)data
//{
//    selectedArea = data;
//}
//
//
-(void)chooseArea
{
    ProvinceViewController *sugVC = [[ProvinceViewController alloc]init];
    
    //    UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:sugVC];
    //    [self  presentViewController:nav animated:YES completion:nil];
    
    [self.navigationController pushViewController:sugVC animated:YES];
}
//
//#pragma mark -LMComBoxViewDelegate
//-(void)selectAtIndex:(int)index inCombox:(ComBoxView *)_combox
//{
//    NSInteger tag = _combox.tag - kDropDownListTag;
//    switch (tag) {
//        case 0:
//        {
//            selectedArea = _combox.titlesList[index];
////            [areaCombox reloadData];
//        }
//            ////NSLog(@"===%@",selectedArea);
//    }
//}



-(void)makeSure
{
    
//    NSString *gender = [NSString stringWithFormat:@"%d",ifboy];
    [_pickview doneClicked];

    
    
}

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString{
    
//    //NSLog(@"选择的生日是几月几号%@",resultString);
    NSString *str = [NSString stringWithFormat:@"%@",resultString];
    NSString *s1 = [str substringToIndex:10];
//    //NSLog(@"kankanwoshishei%@,%@,%@",s1,str,resultString);
    _birthdayTime = s1;

    
    NSString *s2 = [s1  stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMdd"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    
    //NSLog(@"locationString:%@==%@",locationString,s2);
    if ([locationString integerValue]>[s2 integerValue]&&[locationString integerValue]-[s2 integerValue]<60000) {
        
        //NSLog(@"11111");
        [self lesGo];
        
        
    } else {
        
        
        //NSLog(@"22222");

        [JKAlert showMessage:@"提示" message:@"不好意思，您的孩子已超出六周岁，已经不在麦苗的观察服务范围内了"];
        
        
    }

    
    
    
    
}
//输入汉字判定
- (BOOL)isChinese:(NSString *)msg{
    
    for (int i = 0; i < [msg length]; i ++) {
        
        unichar a = [msg characterAtIndex:i];
        
        if ((int)a < 255) {
            
            return NO;
        }
    }
    
    return YES;
}

-(void)lesGo{
    
    
    
    if ([_babyName.text isEqualToString:@""]) {
        
        [self ShowProgressHUDwithMessage:@"请输入名字"];
    }else  if (![self isChinese:_babyName.text] ) {
        ////NSLog(@"请选择地址");
        [self ShowProgressHUDwithMessage:@"宝宝姓名只能为中文"];
    }

    else if  ([ifboy isEqualToString:@""]) {
        [self ShowProgressHUDwithMessage:@"请选择性别"];
    }   else if (_birthdayTime ==nil) {
        [self ShowProgressHUDwithMessage:@"请选择生日"];
    }
    else  if ([areaManager shareInstance].areaId ==nil) {
        ////NSLog(@"请选择地址");
        [self ShowProgressHUDwithMessage:@"请选择地址"];
    }
    
    else
    {
        ////NSLog(@"======================%@",_birthdayTime);
        
        //        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
        //        NSString *str = babyName.text;
        //        NSString *retStr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        ////        NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];
        //        ////NSLog(@"==================%@",retStr);
        
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *ID = [user objectForKey:@"ID"];
        
        NSDictionary *param = @{@"userId": ID,@"name": _babyName.text,@"gender":ifboy,@"birthday": _birthdayTime,@"area":[areaManager shareInstance].areaId,@"babyId":_myBabyId};
        
        ////NSLog(@"字典里得数据位%@",param);
        
        [UserDAL getAddBabyParams: param withBlock:^(NSDictionary *data, NSError *error) {
            if (data) {
//                NSArray *dataList = data[@"dataList"];
//                [BabyManager shareInstance].babyId = dataList[dataList.count-1][@"ID"];
//                [BabyManager shareInstance].babyName = dataList[dataList.count-1][@"babyName"];
//                [BabyManager shareInstance].babyTime = dataList[dataList.count-1][@"babyAge"];
//                //NSLog(@"hahahahahaah%@,%@,%@",[BabyManager shareInstance].babyId,[BabyManager shareInstance].babyName,[BabyManager shareInstance].babyTime);

                NSString *babyName = @"";
                NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
                [user1 setObject:babyName forKey:@"babyName"];
                
                
                NSString *babyAge = @"";
                NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
                [user2 setObject:babyAge forKey:@"babyAge"];

                
                NSString *nasty = @"0";
                NSUserDefaults *user3 = [NSUserDefaults standardUserDefaults];
                [user3 setObject:nasty forKey:@"nasty"];
                


                [self ShowProgressHUDwithMessage:data[@"msg"]];
//                [self dismissViewControllerAnimated:YES completion:nil];
                
                
                
                
               
                myTabBarViewController * myTableView = [[myTabBarViewController alloc]init]; // previous page transfered
                myTableView.selectedIndex = 4;
                [self  presentViewController:myTableView animated:YES completion:nil];

                
            }
            else
            {
                
            }
        }];
        
    }

    
}

-(void)back
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
}


#pragma mark - HUD
- (void)ShowProgressHUDwithMessage:(NSString *)msg
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    hud.dimBackground = NO;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
